package top.mcwebsite.playandroid.business.login.impl.ui


import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.lib.router.annotation.Route
import top.mcwebsite.playandroid.business.login.impl.vm.LoginIntent
import top.mcwebsite.playandroid.business.login.impl.vm.LoginUiEffect
import top.mcwebsite.playandroid.business.login.impl.vm.LoginUiState
import top.mcwebsite.playandroid.business.login.impl.vm.LoginViewModel
import top.mcwebsite.playandroid.common.constant.RouteConfig


@Route(RouteConfig.Login.PATH)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen() {
    val viewModel = viewModel<LoginViewModel>()
    val uiState by viewModel.uiStateFlow.collectAsState()
    viewModel.HandleUiEffect {
        when (it) {
            LoginUiEffect.GoForgetPasswordEffect -> {
                EasyRouter.navigate("xx")
            }

            LoginUiEffect.GoRegisterEffect -> {
                EasyRouter.navigate(RouteConfig.Register.PATH)
            }

            LoginUiEffect.LoginSuccessEffect -> {
                EasyRouter.popBackStack()
            }
        }
    }
    val snackbarHostState = remember { SnackbarHostState() }
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text("登录")
                }, navigationIcon = {
                    IconButton(onClick = {
                        EasyRouter.popBackStack()
                    }) {
                        Icon(Icons.Default.ArrowBack, null)
                    }
                }
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) },
    ) { innerPadding ->
        LaunchedEffect(uiState.toastMessage) {
            uiState.toastMessage?.let {
                snackbarHostState.showSnackbar(it)
                viewModel.toastMessageShown()
            }
        }
        LoginScreenContent(innerPadding, uiState) {
            viewModel.sendIntent(it)
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun LoginScreenContent(
    innerPadding: PaddingValues,
    uiState: LoginUiState,
    sendIntent: (LoginIntent) -> Unit
) {
    Box(
        modifier = Modifier
            .padding(innerPadding)
            .padding(top = 50.dp)
            .padding(horizontal = 20.dp)
    ) {
        Column {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(text = "用户登录", style = MaterialTheme.typography.titleLarge)
                CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)) {
                    Text(
                        text = "请使用 WanAndroid 账号登录",
                        style = MaterialTheme.typography.labelMedium,
                    )
                }
            }
            Spacer(modifier = Modifier.height(40.dp))
            Log.d("mengchen", "uiState.username = ${uiState.username}")
            TextField(
                value = uiState.username,
                onValueChange = {
                    sendIntent(LoginIntent.OnInputUsernameIntent(it))
                },
                singleLine = true,
                colors = TextFieldDefaults.colors(
                    unfocusedIndicatorColor = Color.Transparent,
                    focusedIndicatorColor = Color.Transparent
                ),
                placeholder = {
                    Text("请输入用户名")
                },
                leadingIcon = {
                    Icon(
                        Icons.Default.Person,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                    )
                },
                modifier = Modifier.fillMaxWidth(),
            )
            Spacer(modifier = Modifier.height(5.dp))
            TextField(
                value = uiState.password,
                onValueChange = {
                    sendIntent(LoginIntent.OnInputPasswordIntent(it))
                },
                singleLine = true,
                colors = TextFieldDefaults.colors(
                    unfocusedIndicatorColor = Color.Transparent,
                    focusedIndicatorColor = Color.Transparent
                ),
                placeholder = {
                    Text("请输入密码")
                },
                leadingIcon = {
                    Icon(
                        Icons.Default.Lock,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                    )
                },
                visualTransformation = PasswordVisualTransformation(),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                modifier = Modifier.fillMaxWidth(),
            )
            Spacer(modifier = Modifier.height(20.dp))
            val keyboardController = LocalSoftwareKeyboardController.current
            Button(
                onClick = {
                    keyboardController?.hide()
                    sendIntent(LoginIntent.RequestLoginIntent)
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = uiState.isCanClickLoginButton
            ) {
                Text(text = "登录")
            }
            Spacer(modifier = Modifier.height(20.dp))
            Row(
                modifier = Modifier.fillMaxWidth()
            ) {
                CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)) {
                    Text(
                        text = "没有账号，去注册",
                        style = MaterialTheme.typography.labelMedium,
                        color = Color(0xFF0000EE),
                        modifier = Modifier.clickable {
                            sendIntent(LoginIntent.GoRegisterIntent)
                        }
                    )
                }
                Spacer(modifier = Modifier.weight(1f))
                CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)) {
                    Text(
                        text = "忘记密码",
                        style = MaterialTheme.typography.labelMedium,
                        color = Color(0xFF0000EE),
                        modifier = Modifier.clickable {
                            sendIntent(LoginIntent.RequestForgetPasswordIntent)
                        }
                    )
                }
            }
        }
    }
}